package cn.lanchengkeji.datafillingsystem.controller;


import cn.lanchengkeji.datafillingsystem.common.Const;
import cn.lanchengkeji.datafillingsystem.common.ResponseBean;
import cn.lanchengkeji.datafillingsystem.common.StatusCode;
import cn.lanchengkeji.datafillingsystem.entity.RqTemplate;
import cn.lanchengkeji.datafillingsystem.entity.Users;
import cn.lanchengkeji.datafillingsystem.exception.CommonException;
import cn.lanchengkeji.datafillingsystem.service.IRqTemplateService;
import cn.lanchengkeji.datafillingsystem.service.IUsersService;
import cn.lanchengkeji.datafillingsystem.utils.Utils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bobobobobo
 * @since 2022-01-18
 */
@RestController
@RequestMapping("/rq-template")
public class RqTemplateController extends BaseController {
	// 日志
	private static Logger logger = LoggerFactory.getLogger(UploadImgController.class);
	@Resource
	private IUsersService iUsersService;
	@Resource
	private IRqTemplateService iRqTemplateService;


	/**
	 *  上传文件
	 * @param imageFile
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
	@Transactional
	@RequiresAuthentication
	public ResponseBean uploadFile(@RequestParam("file") MultipartFile imageFile,@RequestParam("templateName") String templateName, HttpServletRequest request)
			throws Exception{

		// 获取登陆系统用户名，存入日志
		Object obj = SecurityUtils.getSubject().getPrincipal();
		logger.debug((String) obj);
		Users user = iUsersService.getUserByName((String) obj);
		if(imageFile == null ){
			return new ResponseBean(StatusCode.UPLOAD_IMG_NOT_NULL,null);
		}


		String uuid = UUID.randomUUID().toString();


		// 获取文件名称
		String fileName = imageFile.getOriginalFilename();
		QueryWrapper<RqTemplate> rqTemplateQueryWrapper = new QueryWrapper<>();
		rqTemplateQueryWrapper.eq(RqTemplate.DEL_FLAG ,Const.DEL_FLAG_NO);
		List<RqTemplate> list = iRqTemplateService.list(rqTemplateQueryWrapper);
		for (RqTemplate rqTemplate : list) {
			if(rqTemplate.getFileName().equals(fileName)){
				throw new CommonException(StatusCode.FILE_NAME_NOT_SAME.getCode(), StatusCode.FILE_NAME_NOT_SAME.getMsg());
			}
			if(rqTemplate.getTemplateName().equals(templateName)){
				throw new CommonException(StatusCode.TEMPLATE_NAME_NOT_SAME.getCode(), StatusCode.TEMPLATE_NAME_NOT_SAME.getMsg());
			}
		}

		// 获取文件大小
		long fileSize = imageFile.getSize();

		// 获取文件类型
		String fileType = fileName.split("\\.")[fileName.split("\\.").length - 1];
		if(!fileType.equals("sht")){
			throw new CommonException(StatusCode.FILE_NOT_TEXT_FOUND.getCode(), StatusCode.FILE_NOT_TEXT_FOUND.getMsg());
		}


		//拼接后台文件名称
		String pathName = "";

		pathName =  File.separator + uuid + "." + FilenameUtils.getExtension(imageFile.getOriginalFilename());
		// 获取当前操作系统
		String os = System.getProperty("os.name");

		String urlString;

		if (os.toLowerCase().startsWith("win")) {
			urlString = Const.UPLOAD_FILE_PATH_WIN;
		} else {
			urlString = Const.UPLOAD_FILE_PATH_LIN + "/" +user.getId();
		}

		//拼接文件路劲
//        String filePathName = realPath + File.separator + pathName;
		String filePathName = urlString + "/"+ fileName;
		logger.info("文件上传路径："+filePathName);

		//判断文件保存是否存在
		File file = new File(filePathName);
		if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {
			//创建文件
			file.getParentFile().mkdirs();
		}

		InputStream inputStream = imageFile.getInputStream();
		FileOutputStream fileOutputStream = new FileOutputStream(file);

		try {

			byte[] buffer = new byte[1024*1024];
			int byteRead = 0;
			while((byteRead=inputStream.read(buffer))!=-1) {
				fileOutputStream.write(buffer,0,byteRead);
			}

		} catch (IOException e) {
			filePathName = null;
			return new ResponseBean(StatusCode.OK_FAIL, e.getMessage());
		} finally {
			try {

				fileOutputStream.flush();
				fileOutputStream.close();
			} catch (IOException e) {
				logger.debug("loadProperties IOException:" + e.getMessage());
			}

			try {
				inputStream.close();
			} catch (IOException e) {
				logger.debug("loadProperties IOException:" + e.getMessage());
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		//原图地址
		map.put("pathUrl", (urlString + pathName).replace("\\\\","\\"));

		// 返回地址

		String addressUrl = "";


		addressUrl = "/" + fileName + "."
				+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
		map.put("pathUrl2",addressUrl);

		FileInputStream fileInputStream = new FileInputStream(filePathName);


		fileInputStream.close();


		map.put("fileSize",fileSize);

		RqTemplate rqTemplate = new RqTemplate();
		rqTemplate.setTemplateName(templateName);
		rqTemplate.setTemplateUrl(filePathName);
		rqTemplate.setFileName(fileName);
		rqTemplate.setUploadTime(new Date());
		rqTemplate.setUploadUser(user.getId());
		rqTemplate.setIsCheck(Const.IS_CHECK_NO);
		rqTemplate.setIsRelease(Const.IS_RELEASE_NO);
		rqTemplate.setIsStart(Const.IS_START_NO);
		iRqTemplateService.save(rqTemplate);


		return new ResponseBean(StatusCode.OK, rqTemplate);
	}

	/**
	 *  修改文件
	 * @param imageFile
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateUploadFile",method = RequestMethod.POST)
	@Transactional
	@RequiresAuthentication
	public ResponseBean updateUploadFile(@RequestParam("file") MultipartFile imageFile, @RequestParam("id") Integer id, HttpServletRequest request)
			throws Exception{

		// 获取登陆系统用户名，存入日志
		Object obj = SecurityUtils.getSubject().getPrincipal();
		logger.debug((String) obj);
		Users user = iUsersService.getUserByName((String) obj);
		if(imageFile == null ){
			return new ResponseBean(StatusCode.UPLOAD_IMG_NOT_NULL,null);
		}

		if(Utils.isEmpty(id)){
			throw new CommonException("101" , "id不能为空");
		}


		String uuid = UUID.randomUUID().toString();


		// 获取文件名称
		String fileName = imageFile.getOriginalFilename();

		// 获取文件大小
		long fileSize = imageFile.getSize();

		// 获取文件类型
		String fileType = fileName.split("\\.")[fileName.split("\\.").length - 1];
		if(!fileType.equals("sht")){
			throw new CommonException(StatusCode.FILE_NOT_TEXT_FOUND.getCode(), StatusCode.FILE_NOT_TEXT_FOUND.getMsg());
		}


		//拼接后台文件名称
		String pathName = "";

		pathName =  File.separator + uuid + "." + FilenameUtils.getExtension(imageFile.getOriginalFilename());
		// 获取当前操作系统
		String os = System.getProperty("os.name");

		String urlString;

		if (os.toLowerCase().startsWith("win")) {
			urlString = Const.UPLOAD_FILE_PATH_WIN;
		} else {
			urlString = Const.UPLOAD_FILE_PATH_LIN + "/" +user.getId();
		}

		//拼接文件路劲
//        String filePathName = realPath + File.separator + pathName;
		String filePathName = urlString + "/"+ fileName;
		logger.info("文件上传路径："+filePathName);

		//判断文件保存是否存在
		File file = new File(filePathName);
		if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {
			//创建文件
			file.getParentFile().mkdirs();
		}

		InputStream inputStream = imageFile.getInputStream();
		FileOutputStream fileOutputStream = new FileOutputStream(file);

		try {

			byte[] buffer = new byte[1024*1024];
			int byteRead = 0;
			while((byteRead=inputStream.read(buffer))!=-1) {
				fileOutputStream.write(buffer,0,byteRead);
			}

		} catch (IOException e) {
			filePathName = null;
			return new ResponseBean(StatusCode.OK_FAIL, e.getMessage());
		} finally {
			try {

				fileOutputStream.flush();
				fileOutputStream.close();
			} catch (IOException e) {
				logger.debug("loadProperties IOException:" + e.getMessage());
			}

			try {
				inputStream.close();
			} catch (IOException e) {
				logger.debug("loadProperties IOException:" + e.getMessage());
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		//原图地址
		map.put("pathUrl", (urlString + pathName).replace("\\\\","\\"));

		// 返回地址

		String addressUrl = "";


		addressUrl = "/" + fileName + "."
				+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
		map.put("pathUrl2",addressUrl);

		FileInputStream fileInputStream = new FileInputStream(filePathName);


		fileInputStream.close();


		map.put("fileSize",fileSize);

		QueryWrapper<RqTemplate> rqTemplateQueryWrapper = new QueryWrapper<>();
		rqTemplateQueryWrapper.eq(RqTemplate.ID , id);
		RqTemplate rqTemplate = iRqTemplateService.getOne(rqTemplateQueryWrapper);
//
//		if(rqTemplate.getTemplateName().equals(templateName)){
//			rqTemplate.setTemplateName(templateName);
//		}else{
//			QueryWrapper<RqTemplate> QueryWrapper = new QueryWrapper<>();
//			QueryWrapper.eq(RqTemplate.DEL_FLAG ,Const.DEL_FLAG_NO);
//			QueryWrapper.eq(RqTemplate.TEMPLATE_NAME ,templateName );
//			List<RqTemplate> list = iRqTemplateService.list(QueryWrapper);
//			if(Utils.notEmpty(list) && list.size() > 0){
//				throw new CommonException(StatusCode.TEMPLATE_NAME_NOT_SAME.getCode(), StatusCode.TEMPLATE_NAME_NOT_SAME.getMsg());
//			}else{
//				rqTemplate.setTemplateName(templateName);
//			}
//		}


		if(rqTemplate.getFileName().equals(fileName)){
			rqTemplate.setFileName(fileName);
		}else{
			QueryWrapper<RqTemplate> QueryWrapper = new QueryWrapper<>();
			QueryWrapper.eq(RqTemplate.DEL_FLAG ,Const.DEL_FLAG_NO);
			QueryWrapper.eq(RqTemplate.FILE_NAME ,fileName);
			List<RqTemplate> list = iRqTemplateService.list(QueryWrapper);
			if(Utils.notEmpty(list) && list.size() > 0){
				throw new CommonException(StatusCode.TEMPLATE_NAME_NOT_SAME.getCode(), StatusCode.TEMPLATE_NAME_NOT_SAME.getMsg());
			}else{
				rqTemplate.setFileName(fileName);
			}
		}
		rqTemplate.setTemplateUrl(filePathName);
		rqTemplate.setUpdateTime(new Date());
		rqTemplate.setUploadTime(new Date());
		rqTemplate.setUploadUser(user.getId());
		rqTemplate.setIsCheck(Const.IS_CHECK_NO);
		rqTemplate.setIsRelease(Const.IS_RELEASE_NO);
		rqTemplate.setIsStart(Const.IS_START_NO);
		iRqTemplateService.updateById(rqTemplate);


		return new ResponseBean(StatusCode.OK, rqTemplate);
	}


	/**
	 * 模板分页查询
	 * @param rqTemplate
	 * @param currentPage
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/page")
	@RequiresAuthentication
	public ResponseBean page(@RequestBody RqTemplate rqTemplate,
	                                  @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer currentPage,
	                                  @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) throws Exception {
		// 获取登陆系统用户名，存入日志
		Object obj = SecurityUtils.getSubject().getPrincipal();
		logger.debug((String) obj);
		Users user = iUsersService.getUserByName((String) obj);
		IPage<RqTemplate> page = new Page(currentPage, pageSize);
		QueryWrapper<RqTemplate> rqTemplateQueryWrapper = new QueryWrapper<>();
		rqTemplateQueryWrapper.eq(RqTemplate.DEL_FLAG , Const.DEL_FLAG_NO);
		if(Utils.notEmpty(rqTemplate.getTemplateName())){
			rqTemplateQueryWrapper.eq(RqTemplate.TEMPLATE_NAME , rqTemplate.getTemplateName());
		}
		if(Utils.notEmpty(rqTemplate.getIsCheck())){
			rqTemplateQueryWrapper.eq(RqTemplate.IS_CHECK , rqTemplate.getIsCheck());
		}
		if(Utils.notEmpty(rqTemplate.getIsRelease())){
			rqTemplateQueryWrapper.eq(RqTemplate.IS_RELEASE , rqTemplate.getIsRelease());
		}
		if(Utils.notEmpty(rqTemplate.getIsStart())){
			rqTemplateQueryWrapper.eq(RqTemplate.IS_START , rqTemplate.getIsStart());
		}
		if(Utils.notEmpty(rqTemplate.getCheckUser())){
			rqTemplateQueryWrapper.eq(RqTemplate.CHECK_USER , rqTemplate.getCheckUser());
		}
		IPage<RqTemplate> iPage = iRqTemplateService.page(page, rqTemplateQueryWrapper);
		return new ResponseBean(StatusCode.OK, iPage);
	}

	/**
	 * 模板审核/发布/启动
	 * @param rqTemplate
	 * @return
	 */
	@RequestMapping(value = "/operate", method = RequestMethod.POST)
	@Transactional
	@RequiresAuthentication
	public ResponseBean operate(@RequestBody RqTemplate rqTemplate)throws Exception {
		// 获取登陆系统用户名，存入日志
		Object obj = SecurityUtils.getSubject().getPrincipal();
		logger.debug((String) obj);
		Users user = iUsersService.getUserByName((String) obj);
		QueryWrapper<RqTemplate> rqTemplateQueryWrapper = new QueryWrapper<>();
		rqTemplateQueryWrapper.eq(RqTemplate.ID , rqTemplate.getId());
		RqTemplate template = iRqTemplateService.getOne(rqTemplateQueryWrapper);
		if(Utils.notEmpty(rqTemplate.getIsStart())){
			template.setIsStart(rqTemplate.getIsStart());
		}
		if(Utils.notEmpty(rqTemplate.getIsRelease())){
			template.setIsRelease(rqTemplate.getIsRelease());
		}
		boolean ret = iRqTemplateService.updateById(template);
		return new ResponseBean(StatusCode.OK, ret);
	}

	/**
	 * 模板删除
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	@Transactional
	@RequiresAuthentication
	public ResponseBean delete(@PathVariable Integer id)throws Exception {
		if(Utils.isEmpty(id)){
			throw new CommonException("101" , "id不能为空");
		}

		boolean ret = iRqTemplateService.removeById(id);
		return new ResponseBean(StatusCode.OK, ret);

	}

	/**
	 * 预览
	 * @param rqTemplate
	 * @return
	 */
	@RequestMapping(value = "/preview", method = RequestMethod.POST)
	@Transactional
	@RequiresAuthentication
	public ResponseBean preview(@RequestBody RqTemplate rqTemplate )throws Exception {
		// todo  调用润乾api预览报表内容
 		return new ResponseBean(StatusCode.OK, null);
	}


	/**
	 * 下载文件
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/downloadExport", method = {RequestMethod.GET, RequestMethod.POST})
	@Transactional
	public ResponseBean downloadExport(@RequestBody RqTemplate rqTemplate , HttpServletResponse response ) throws Exception {
//		String path = trainPoincareVO.getResultPath();
		String path = rqTemplate.getTemplateUrl();
		try {
			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 取得文件的后缀名。
			String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.setHeader("content-type", "csv/html;charset=utf-8");
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return new ResponseBean(StatusCode.OK, "");
	}



}
